package com.weaver.qfengx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;

/**
 * Created by YeShengtao on 2020/8/7 11:33
 */
public class JsonUtils {

    public static <T> T jsonToBean(JSONObject jsonObject, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                String value = jsonObject.getString(fieldName);
                field.setAccessible(true);
                field.set(t, value);
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String toJson(Object object) {
        try {
            return JSON.toJSONString(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
